package com.gridmobi.xrtb.dspcounter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.gridmobi.xrtb.common.HttpClientUtil;
import com.gridmobi.xrtb.handler.Mailer;
import com.gridmobi.xrtb.handler.monitor.RtbStatus;
import com.gridmobi.xrtb.handler.monitor.SimpleData;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * RTB实时数据更新 以及reindex
 *
 * @author huangyongchao
 */
@Component
public class DspCounterJob {
    @Value("${rtbname}")
    private String rtbname;
    public static String CURRENT_DATE = LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
    public static int CURRENT_HOUR = LocalDateTime.now(ZoneOffset.UTC).getHour();

    @Scheduled(cron = "1 0 */1 * * ?")
    public void changeState() {
        CURRENT_DATE = LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        CURRENT_HOUR = LocalDateTime.now(ZoneOffset.UTC).getHour();
    }

    private static final Logger logger = LoggerFactory.getLogger(DspCounterJob.class);

    @Value("${dsp.recordclicks}")
    private String recordclicksUrl;
    @Value("${dsp.getdailybudget}")
    private String getdailybudgetUrl;

    @Autowired
    private Mailer mailer;
    @Autowired
    private RestTemplate restTemplate;

    @Scheduled(cron = "1 */1 * * * ?")
    public void checkDailyBudget() {
        try {
            RtbStatus.BID_LOCK_BY_BUDGET_ERROR = true;
            String resp = HttpClientUtil.get(getdailybudgetUrl);
            logger.warn("checkDailyBudget:" + resp);

            if (StringUtils.isNotBlank(resp)) {
                JSONArray respa = JSONArray.parseArray(resp);
                respa.forEach(obj -> {

                    JSONObject json = (JSONObject) obj;
                    SimpleData.CAMPAIGNS_DAYLY_BUDGET_CACHE.put(json.getLong("cid"), json.getFloatValue("cost"));
                    if (json.getFloatValue("cost") > 50) {
                        RtbStatus.BID_LOCK_BY_BUDGET_ERROR = true;

                    }
                });
                RtbStatus.BID_LOCK_BY_BUDGET_ERROR = false;
            }


        } catch (Exception e) {
            RtbStatus.BID_LOCK_BY_BUDGET_ERROR = true;
            e.printStackTrace();
            mailer.sendErrorMail("RTB API ERROR:" + "checkDailyBudget" + rtbname, e.getMessage());

        }

    }

    @Scheduled(cron = "1 */1 * * * ?")
    public void sendClicks() {
        try {
            RtbStatus.BID_LOCK_BY_CLICKS_ERROR = true;
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            Map<String, DspCounter> oldMap = DspCounterHandler.CURRENT_COUNTER;
            if (oldMap.size() == 0) {
                return;
            }
            DspCounterHandler.CURRENT_COUNTER = Maps.newConcurrentMap();
            try {
                Map<String, DspCounterDto> dtoMap = Maps.newConcurrentMap();
                oldMap.forEach((k, v) -> {
                    dtoMap.put(k, new DspCounterDto(
                            v.getClicks().get(),
                            v.getImprs().get(),
                            v.getBids().get(),
                            v.getWins().get(),
                            v.getConvs().get(),
                            v.getCosts().get()));
                });
                HttpEntity entity = new HttpEntity(dtoMap);
                logger.warn("sendDspClicks:" + JSONObject.toJSONString(dtoMap));
                restTemplate.exchange(recordclicksUrl, HttpMethod.POST, entity, String.class);
                RtbStatus.BID_LOCK_BY_CLICKS_ERROR = false;

            } catch (Exception e) {
                e.printStackTrace();
                RtbStatus.BID_LOCK_BY_CLICKS_ERROR = true;

                DspCounterHandler.CURRENT_COUNTER = oldMap;
            }

        } catch (Exception e) {
            RtbStatus.BID_LOCK_BY_CLICKS_ERROR = true;

            e.printStackTrace();
            mailer.sendErrorMail("RTB API ERROR:" + "sendDspClicks:" + rtbname, e.getMessage());


        }

    }
}

